import {
  mAddProductFile,
  mDownInstructionBook,
  mSelectProductFileByPage,
  mUploadInstructionBook,
  mUploadInstructionVideo,
  mUploadProductTypeImage
} from '@/api/others'
import {selectItemByCode} from '@/api/information'
import useGlobalAPI from '@/hooks/useGlobalAPI'

import {FormInstance} from 'ant-design-vue'
import {PropType} from 'vue'
import './components.less'
import {downFile} from '@/libs/toolkit'
import {CoustomTableFn} from '@/components/table'
import {getStorage} from '@/libs/localstoreage'
import {getUserId} from '@/libs/auth'
import {message} from '@/libs/global/antDesignVue'

/** 状态数据 */
interface Others_proFileList_state {
  /**资料类型列表 */
  proFileTypeList: SysDict.Item[]
  /**弹窗 */
  modal: {
    /**弹窗 关闭*/
    visible: boolean
    /**弹窗 类型*/
    type: 'addProductFile' | 'showVideo' | 'showWorldOrPdf' | null
    /**弹窗 标题*/
    title: string

    data: ProductFile.DataSource | null
    wrapClassName?: string
  }
  table: CTable<ProductFile.DataSource>
  search: {
    fileTypeCode: string
    fileName: string
    fileTypeName: string
  }
  addProductFileFormData: {
    fileTypeCode: string
    fileDesc: string
    fileUrl: string
    fileName: string
    filePath: string
    uploadUser: string
  }
}
export let others_proFileList_state = reactive<Others_proFileList_state>({
  proFileTypeList: [],
  modal: {
    visible: false,
    type: null,
    title: '',
    data: null,
    wrapClassName: ''
  },
  table: {
    dataSource: [],
    loading: false,
    pagination: {
      page: 1,
      size: 20
    },
    total: 0,
    onPaginatiChange({page, size}) {
      let {pagination} = toRefs(others_proFileList_state.table)
      pagination.value.page = page
      pagination.value.size = size
      getTableDatas()
    }
  },
  search: {
    fileTypeCode: '',
    fileName: '',
    fileTypeName: ''
  },
  addProductFileFormData: {
    fileTypeCode: '0046',
    fileDesc: '',
    fileUrl: '',
    fileName: '',
    filePath: '',
    uploadUser: ''
  }
})

/**获取表格数据 */
export async function getTableDatas(isGetData?: boolean) {
  let {dataSource, pagination, total: tableTotal, loading} = toRefs(others_proFileList_state.table)
  loading.value = true

  let {search} = toRefs(others_proFileList_state)
  let defaultData = {
    page: pagination.value.page,
    size: pagination.value.size,
    start: 0,
    fileTypeCode: search.value.fileTypeCode,
    fileName: search.value.fileName
  }
  let res = await mSelectProductFileByPage(defaultData).catch(err => {
    loading.value = false
  })
  if (!res) return
  if (isGetData) {
    loading.value = false
    return res.data
  }
  let {list, total} = res.data
  dataSource.value = list
  tableTotal.value = total
  loading.value = false
}

/**获取所有资料类型 */
export async function getProFileType() {
  let res = await selectItemByCode({code: '0047'}).catch(err => {})
  if (!res) return
  let {proFileTypeList, search} = toRefs(others_proFileList_state)
  proFileTypeList.value = res.data
  search.value.fileTypeCode = res.data[0].dictCode
  search.value.fileTypeName = res.data[0].dictName
  getTableDatas()
}

/**左侧搜索栏 input keyup事件 */
const handle_search_input_keyup = (e: any) => {
  console.log(e)
  let {key} = e
  switch (key) {
    case 'Enter':
      getTableDatas()
      break
  }
}

/**关闭弹窗 */
const close_modal = () => {
  let {visible, type, title} = toRefs(others_proFileList_state.modal)
  visible.value = false
  setTimeout(() => {
    type.value = null
    title.value = ''
  }, 300)
}

/**弹窗 表单 操作产品资料 */
const ModalOfAddProductFile = defineComponent({
  name: 'ModalOfAddTeachingvideo',
  setup(props, {emit}) {
    let {store} = useGlobalAPI()

    let {fileTypeCode, fileTypeName} = toRefs(others_proFileList_state.search)

    let userId = computed(() => store.getters['login/GETPLATFORMUSERID'])

    let formRef = ref<FormInstance>()

    let uploadFilName = ref('')

    let {addProductFileFormData} = toRefs(others_proFileList_state)

    /**提交表单且数据验证成功后回调事件 */
    const handle_form_finish = async () => {
      console.log(userId.value)

      if (!userId.value) return
      if (!addProductFileFormData.value.filePath) {
        message.error('未上传文件')
        return
      }
      if (!addProductFileFormData.value.fileName) {
        message.error('未输入文件名称')
        return
      }
      console.log('开始添加产品资料', addProductFileFormData.value)
      let res = await mAddProductFile({
        ...addProductFileFormData.value,
        uploadUser: userId.value
      }).catch(err => {})
      if (res) getTableDatas()

      returnEmit()
    }

    /** 提交表单且数据验证失败后回调事件 */
    const handle_form_finish_failed = () => {
      console.log('handle_form_finish_failed')
      returnEmit()
    }

    /**表单取消按钮点击 */
    const handle_form_cancel = () => {
      returnEmit()
    }

    /**清空表单 关闭外层弹框 */
    const returnEmit = () => {
      addProductFileFormData.value = {
        fileTypeCode: '0046',
        fileDesc: '',
        fileUrl: '',
        fileName: '',
        filePath: '',
        uploadUser: ''
      }
      close_modal()
    }

    return () => {
      return (
        <a-form
          v-model={[formRef, 'ref']}
          name='addInsbook'
          model={addProductFileFormData.value}
          label-col={{span: 4}}
          wrapper-col={{span: 16}}
          onFinish={handle_form_finish}
          onFinishFailed={handle_form_finish_failed}
        >
          <a-form-item label='上传文件' name='filePath'>
            <div class='grid grid-cols-4'>
              <div class='col-span-3 flex justify-start items-center'>
                {addProductFileFormData.value.filePath && addProductFileFormData.value.fileUrl ? (
                  <span class='text-success'>{`${uploadFilName.value} 上传完成`}</span>
                ) : (
                  <span class='text-info'>请选择文件</span>
                )}
              </div>
              <label>
                <a-input
                  id='uploadInsBook'
                  class='hidden'
                  type='file'
                  accept={
                    fileTypeCode.value === '0046'
                      ? '.mp4'
                      : fileTypeCode.value === '0045'
                      ? '.doc,.docx,.rtf,.pdf'
                      : fileTypeCode.value === '0153'
                      ? '.png,.jpg'
                      : ''
                  }
                  onChange={async (e: any) => {
                    if (e.target.files.length <= 0) return
                    let formData = new FormData()
                    formData.append('file', e.target.files[0])
                    let res: CustomRequest<ProductFile.DataSource> | void
                    console.log(e, fileTypeCode.value)

                    if (fileTypeCode.value === '0045') {
                      res = await mUploadInstructionBook(formData).catch(err => {
                        uploadFilName.value = ''
                        addProductFileFormData.value.filePath = ''
                        addProductFileFormData.value.fileUrl = ''
                      })
                    } else if (fileTypeCode.value === '0046') {
                      res = await mUploadInstructionVideo(formData).catch(err => {
                        uploadFilName.value = ''
                        addProductFileFormData.value.filePath = ''
                        addProductFileFormData.value.fileUrl = ''
                      })
                    } else if (fileTypeCode.value === '0153') {
                      res = await mUploadProductTypeImage(formData).catch(err => {
                        uploadFilName.value = ''
                        addProductFileFormData.value.filePath = ''
                        addProductFileFormData.value.fileUrl = ''
                      })
                    }
                    if (!res) return
                    uploadFilName.value = e.target.files[0].name
                    addProductFileFormData.value.filePath = res.data.filePath
                    addProductFileFormData.value.fileUrl = res.data.fileUrl
                  }}
                />
                <a-button onClick={() => document.getElementById('uploadInsBook')?.click()}>
                  上传{fileTypeName.value}
                </a-button>
              </label>
            </div>
          </a-form-item>
          <a-form-item label='名称' name='fileName'>
            <a-input v-model={[addProductFileFormData.value.fileName, 'value']} />
          </a-form-item>
          <a-form-item label='备注' name='fileDesc'>
            <a-input v-model={[addProductFileFormData.value.fileDesc, 'value']} />
          </a-form-item>
          <a-form-item>
            <a-button type='primary' class='float-right mx-4' html-type='submit'>
              提交
            </a-button>
            <a-button class='float-right mx-4' onClick={handle_form_cancel}>
              取消
            </a-button>
          </a-form-item>
        </a-form>
      )
    }
  }
})

/**弹窗 表单 查看操作视频 */
const ModalOfShowVideo = defineComponent({
  name: 'ModalOfShowVideo',
  setup() {
    let {data} = toRefs(others_proFileList_state.modal)
    let url = computed(() => {
      return data.value?.fileUrl ? data.value?.fileUrl + data.value?.filePath : ''
    })
    return () => (
      <video class='h-96 mx-auto' controls>
        <source src={url.value} type='video/mp4' />
      </video>
    )
  }
})

// /**弹窗 表单 查看World或者Pdf文档 */
// const ModalOfShowWorldOrPdf = defineComponent({
//   name: 'ModalOfShowVideo',
//   props: {
//     record: {
//       type: Object as PropType<ProductFile.DataSource | null>,
//       default: null,
//     },
//   },
//   setup(props) {
//     let {visible, type, title, data} = toRefs(others_proFileList_state.modal)
//     let {record} = toRefs(props)
//     const showWorldOrPdf = () => {
//       visible.value = true
//       type.value = 'showWorldOrPdf'
//       title.value = record.value?.fileName || ''
//       data.value = record.value
//     }
//     const showVideo = () => {
//       visible.value = true
//       type.value = 'showVideo'
//       title.value = record.value?.fileName || ''
//       data.value = record.value
//     }
//     return () => {
//       let filePathSplit = data.value?.filePath.split('/') || []
//       let fileSuf = filePathSplit[filePathSplit.length - 1].split('.')[1]
//       switch (fileSuf) {
//         case 'doc':
//         case 'docx':
//         case 'rtf':
//           return <div>world</div>
//         case 'pdf':
//           console.log('pdf路径', data.value?.filePath)
//           return (
//             <ModalContentOfPDF
//               PDFUrl={data.value?.filePath}
//             ></ModalContentOfPDF>
//           )
//       }
//     }
//   },
// })

/** 左侧搜索 关键字 */
export const ViewLeftNav = defineComponent({
  name: 'ViewLeft',
  setup() {
    let {search} = toRefs(others_proFileList_state)

    return () => (
      <div class='h-mainViewNav  border-b border-default px-4 grid place-items-center overflow-hidden'>
        <a-input
          v-model={[search.value.fileName, 'value']}
          placeholder='输入名称'
          onKeyup={(e: any) => handle_search_input_keyup(e)}
        ></a-input>
      </div>
    )
  }
})

/** 左侧搜索 筛选区域 */
export const ViewLeftFilter = defineComponent({
  name: 'ViewLeftFilter',
  setup(props, {emit}) {
    let {search, proFileTypeList} = toRefs(others_proFileList_state)
    let {pagination} = toRefs(others_proFileList_state.table)
    const handle_proFileType_checked = (dictCode: string, dictName: string) => {
      console.log(dictCode)
      search.value.fileTypeCode = dictCode
      search.value.fileTypeName = dictName
      pagination.value.page = 1
      getTableDatas()
    }
    onMounted(() => {
      getProFileType()
    })
    return () => (
      <div class='viewLeftFilter overflow-auto relative'>
        {proFileTypeList.value.map((item, idx) => (
          <label for={'viewLeftFilter' + idx}>
            <input
              type='radio'
              name='viewLeftFilter'
              id={'viewLeftFilter' + idx}
              class='hidden input_acitve'
              checked={search.value.fileTypeCode === item.dictCode}
            ></input>
            <div
              class='viewLeftFilter-line flex justify-between items-center text-sm truncate cursor-pointer py-2 hover:bg-primary_light'
              onClick={() => handle_proFileType_checked(item.dictCode, item.dictName)}
            >
              <div class='viewLeftFilter-icon w-1/12'>
                <i class='iconfont'></i>
              </div>
              <div class='viewLeftFilter-label w-5/12'>{item.dictName}</div>
              <div class='viewLeftFilter-value w-5/12 text-right pr-1 text-info text-xs'>
                {item.dictDesc}
              </div>
            </div>
          </label>
        ))}
      </div>
    )
  }
})

/** 左侧搜索 底部搜索 */
export const ViewLeftFooter = defineComponent({
  name: 'ViewLeftFooter',
  setup() {
    let {search} = toRefs(others_proFileList_state)
    const handle_search_reset = () => {
      search.value.fileName = ''
      getProFileType()
    }
    return () => (
      <div class='h-full flex justify-end items-center'>
        <a-button type='primary' onClick={handle_search_reset}>
          重置
        </a-button>
        <a-button class='ml-4 ' type='primary' onClick={getTableDatas}>
          查询
        </a-button>
      </div>
    )
  }
})
/** 表格 操作栏 */
export const TypeHandleBtn = defineComponent({
  props: {
    record: {
      type: Object as PropType<ProductFile.DataSource>,
      default: {}
    }
  },
  setup(props) {
    let {router} = useGlobalAPI()
    let {visible, title, type} = toRefs(others_proFileList_state.modal)

    const handle_type_edit_btn_click = () => {
      console.log(props.record)
      // visible.value = true
      // type.value = 'editType'
      // title.value =
      //     '修改参数: ' +
      //     props.record.devTypeCode +
      //     '——' +
      //     props.record.devTypeDataCode

      // //给修改表单数据源赋值
      // edit_source.value.devTypeDataDesc =
      //     props.record.devTypeDataDesc || ''
      // edit_source.value.devTypeDataId = props.record.devTypeDataId
      // edit_source.value.devTypeDataValue =
      //     props.record.devTypeDataValue || ''
    }

    return () => (
      <div>
        <span
          class='mr-2 text-primary border-b cursor-pointer'
          onClick={handle_type_edit_btn_click}
        >
          编辑
        </span>
      </div>
    )
  }
})
/** 表格 */
const CoustomTable = CoustomTableFn<ProductFile.DataSource>()
export const TypeTable = defineComponent({
  name: 'TypeTable',
  setup(props) {
    let {dataSource, loading, total, onPaginatiChange} = toRefs(others_proFileList_state.table)
    let {page, size} = toRefs(others_proFileList_state.table.pagination)

    let columns: CColumn<ProductFile.DataSource>[] = [
      {
        title: '名称',
        dataIndex: 'fileName',
        ellipsis: true
      },
      {
        title: '上传者',
        dataIndex: 'uploadUser',
        ellipsis: true
      },
      {
        title: '上传时间',
        dataIndex: 'createTime',
        ellipsis: true
      },
      {
        title: '文件地址',
        dataIndex: 'fileUrl',
        width: 500,
        ellipsis: true
      },
      {
        title: '备注',
        dataIndex: 'fileDesc',
        ellipsis: true
      },
      {
        title: '操作',
        dataIndex: 'utils',
        isUtil: true,
        width: 140
      }
    ]

    return () => (
      <CoustomTable
        dataSource={dataSource.value}
        loading={loading.value}
        rowKey='fileId'
        columns={columns}
        pagination={{
          page: page.value,
          size: size.value,
          total: total.value
        }}
        onPaginationChange={data => onPaginatiChange.value(data)}
      >
        {{
          util: (record: ProductFile.DataSource) => <TypeHandleBtn record={record}></TypeHandleBtn>,
          bodyCell: (
            text: string,
            record: ProductFile.DataSource,
            index: number,
            column: CColumn<ProductFile.DataSource>
          ) => {
            if (column.dataIndex === 'fileUrl') return record.fileUrl + record.filePath
          }
        }}
      </CoustomTable>
    )
  }
})

/** 弹窗 */
export const TypeModel = defineComponent({
  setup(props, {emit}) {
    let {visible, type, title, wrapClassName} = toRefs(others_proFileList_state.modal)
    const handle_form_finish = () => {
      close_modal()
      getTableDatas()
    }
    return () => {
      let dynamicCom = <div></div>
      switch (type.value) {
        case 'addProductFile':
          dynamicCom = <ModalOfAddProductFile></ModalOfAddProductFile>
          break
        case 'showVideo':
          dynamicCom = <ModalOfShowVideo></ModalOfShowVideo>
          break
        // case 'showWorldOrPdf':
        //   dynamicCom = <ModalOfShowWorldOrPdf></ModalOfShowWorldOrPdf>
        //   break
      }
      return (
        <a-modal
          visible={visible.value}
          title={title.value}
          footer={null}
          onCancel={() => {
            handle_form_finish()
          }}
          class={wrapClassName?.value}
          destroyOnClose
        >
          {dynamicCom}
        </a-modal>
      )
    }
  }
})

/** 表格上方操作栏 */
export const TypeMainViewNav = defineComponent({
  setup() {
    let {router} = useGlobalAPI()
    let {visible, type, title} = toRefs(others_proFileList_state.modal)
    const handle_add = () => {
      visible.value = true
      type.value = 'addProductFile'
      title.value = '添加' + others_proFileList_state.search.fileTypeName
      others_proFileList_state.addProductFileFormData = {
        fileTypeCode: others_proFileList_state.search.fileTypeCode,
        fileDesc: '',
        fileUrl: '',
        fileName: '',
        filePath: '',
        uploadUser: ''
      }
    }
    return () => (
      <div class='h-full bg-white px-4 flex justify-start items-center'>
        <a-button type='primary' class='mr-4' onClick={() => handle_add()}>
          添加资料
        </a-button>
      </div>
    )
  }
})
